package com.lesama.binarysearch;

public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        System.out.println(binarySearch(arr, 9));
        System.out.println(binarySearch(arr, 0));
        System.out.println(binarySearch(arr, 1));
    }

    private static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length;
        while(left <= right) {
            int mid = (left + right) / 2;
            if(arr[mid] > target) {
                right = mid - 1;
            } else if (arr[mid] < target) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}
